package com.dingding.service.mall.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.common.core.beans.UserCoupon;
import com.dingding.common.core.beans.Userintegraldetail;
import com.dingding.common.core.util.ToolUtil;
import com.dingding.facade.account.integral.dto.GetUserIntegralDetailDTO;
import com.dingding.facade.account.integral.dto.UserInregralOperateDTO;
import com.dingding.facade.account.integral.enums.IntegralTradeTypeEnum;
import com.dingding.facade.account.integral.service.IUserIntegralService;
import com.dingding.facade.mall.dto.BannerScrollImg;
import com.dingding.facade.mall.dto.CommodityInfo;
import com.dingding.facade.mall.dto.CommodityInfoPic;
import com.dingding.facade.mall.dto.CommodityInfoRes;
import com.dingding.facade.mall.dto.MallItem;
import com.dingding.facade.mall.dto.UserCommodityOrderDTO;
import com.dingding.facade.mall.dto.UserIntegraDetailRecordRes;
import com.dingding.facade.mall.dto.UserMallIndexRes;
import com.dingding.facade.mall.service.IUserMallFacade;
import com.dingding.facade.mall.status.StatusCode;
import com.dingding.facade.user.service.IUserInfoFacade;
import com.dingding.facde.activity.service.IMallUserCouponService;
import com.dingding.service.mall.dao.IBannerImageDao;
import com.dingding.service.mall.dao.ICommodityDao;
import com.dingding.service.mall.dao.ICommodityInfoDao;
import com.dingding.service.mall.dao.ICommodityInfoPicDao;
import com.dingding.service.mall.dao.IUserCommodityOrderDao;
import com.dingding.service.mall.dao.IUserIntegralDao;

@Component("userMallFacade")
public class UserMallFacadeImpl implements IUserMallFacade {

	@Resource(name = "bannerImageDao")
	private IBannerImageDao bannerImageDao; // banner图片dao

	@Resource(name = "userIntegralDao")
	private IUserIntegralDao userIntegralDao; // 用户积分dao

	@Resource(name = "commodityDao")
	private ICommodityDao commodityDao; // 商品dao

	@Resource(name = "userCommodityOrderDao")
	private IUserCommodityOrderDao userCommodityOrderDao;// 商城订单dao

	@Resource(name = "commodityInfoDao")
	private ICommodityInfoDao commodityInfoDao; // 商品详情dao

	@Resource(name = "commodityInfoPicDao")
	private ICommodityInfoPicDao commodityInfoPicDao; // 商品详情图片dao

	@Resource(name = "userIntegralService") // 账户操作Service
	private IUserIntegralService userIntegralService;

	@Resource(name = "mallUserCouponService") // 用户优惠券Service
	private IMallUserCouponService mallUserCouponService;

	@Resource(name = "userInfoFacade")
	private IUserInfoFacade userInfoFacade; // 用户信息操作接口

	/**
	 * @Description: 获取商城首页信息
	 * @param userId
	 *            用户的登录id
	 * @author fengshuonan
	 * @return UserMallIndexRes
	 */
	@Transactional(readOnly = true)
	public UserMallIndexRes getMallIndexInfo(String userId) {

		if (ToolUtil.isBlank(userId)) {
			return null;
		}

		/**
		 * 1.获取商城主页banner图片列表
		 */
		List<BannerScrollImg> banners = this.bannerImageDao.getBannerImageList(1, 1);

		/**
		 * 2.获取用户积分
		 */
		double userInte = userIntegralDao.getUserIntegral(userId);

		/**
		 * 3.获取商品列表
		 */
		List<MallItem> items = commodityDao.getMallItems();

		UserMallIndexRes res = new UserMallIndexRes();
		res.setBannerList(banners);
		res.setIntegralSum(userInte);
		res.setItemList(items);

		return res;
	}

	/**
	 * @Description: 用户购买商品
	 * @param userId
	 *            用户id
	 * @param itemId
	 *            商品主键id
	 * @author zhouxuan
	 * @return int 状态码（操作成功或失败）
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public synchronized int buyItem(String userId, String itemId) {

		if (ToolUtil.validateParas(userId, itemId)) {
			return StatusCode.NULL_PARA;
		}

		// 获取商品类型
		int itemType = this.commodityDao.getItemTypeById(itemId);

		// 查询异常
		if (itemType == 0) {
			return StatusCode.FAILED;
		}

		// 不是实物商品
		if (itemType != 4) {
			// 获取用户积分和商品积分
			double userInte = this.userIntegralDao.getUserIntegral(userId);
			double itemInte = this.commodityDao.getItemPriceById(itemId);
			// 如果用户余额不足
			if (userInte - itemInte < 0) {
				return StatusCode.MONEY_NOT_ENOUGH;
			}
			// 获取商品数量剩余情况（true 有库存 false 没库存）
			if (!this.commodityDao.getItemStockStatus(itemId)) {
				return StatusCode.ITEMS_NOT_ENOUGH;
			}
			// 生成商品订单
			if (this.userCommodityOrderDao.createShopOrder(userId, itemId, itemInte) == false) {
				return StatusCode.ORDER_CREATE_ERROR;
			}

			// 给用户添加优惠券
			UserCoupon userCoupon = new UserCoupon();
			userCoupon.setUcId(ToolUtil.getUid());
			userCoupon.setLoginId(userId); // 用户id
			userCoupon.setCouponId(Integer.parseInt(itemId)); // 商品id
			userCoupon.setCouponType(itemType); // 优惠券类型
			userCoupon.setCouponMoney(2); // 优惠券价格    
			userCoupon.setCouponStatus(2); // 优惠券状态

			// 获取时间
			Date date = new Date();

			// 计算有效期
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			calendar.add(calendar.DATE, this.commodityDao.getExpiredDate(itemId));

			// 设置时间
			userCoupon.setCreateTime(date);
			userCoupon.setExpiredTime(calendar.getTime());

			// 修改商品数量并返回
			if (this.mallUserCouponService.addCouponForUser(userCoupon)) {
				// 更新商品数量
				this.commodityDao.updateItemNums(itemId, -1);
				// 修改用户优惠券数目
				this.userInfoFacade.addUserCoupon(userId);
				// 扣除账户积分
				UserInregralOperateDTO userInregralOperateDTO = new UserInregralOperateDTO();
				userInregralOperateDTO.setUserId(userId);
				userInregralOperateDTO.setIntegral(new BigDecimal(itemInte));
				userInregralOperateDTO.setIntegralTradeTypeEnum(IntegralTradeTypeEnum.Exchange);// 交易类型为兑换
				userInregralOperateDTO.setTradContent(getTradContent(itemType));// 设置交易内容
				userIntegralService.deductUserInregral(userInregralOperateDTO);

				return StatusCode.SUCCESS;
			}

		}
		return StatusCode.FAILED;
	}

	/**
	 * @Description: 获取积分记录列表
	 * @param userId
	 *            用户的登录id
	 * @author zhouxuan
	 * @return List<UserCommodityOrderDTO>
	 * 
	 */

	@Transactional(readOnly = true)
	public List<UserCommodityOrderDTO> getUserCommodityOrderList(String userId) {

		if (ToolUtil.validateParas(userId)) {
			return null;
		}

		// 获取用户商品订单列表
		List<UserCommodityOrderDTO> userCommodityOrderDTOs = this.userCommodityOrderDao
				.getUserCommodityOrderList(userId);

		return userCommodityOrderDTOs;

	}

	/**
	 * @Description: 获取商品详情
	 * @param commodityId
	 *            商品id
	 * @author zhouxuan
	 * @return CommodityInfo
	 */

	@Transactional(readOnly = true)
	public CommodityInfoRes getCommodityInfoRes(String commodityId) {

		CommodityInfoRes commodityInfoRes = new CommodityInfoRes();

		// 获取商品详细信息
		CommodityInfo commodityInfo = this.commodityInfoDao.getCommodityInfo(commodityId);
		List<CommodityInfoPic> commodityInfoPic = this.commodityInfoPicDao.getCommodityInfoPic(commodityId);

		commodityInfoRes.setCommodityInfo(commodityInfo);
		commodityInfoRes.setCommodityInfoPic(commodityInfoPic);

		return commodityInfoRes;
	}

	/**
	 * @Description: 根据优惠券类型获取交易内容
	 * @param type
	 *            优惠券类型
	 * @author fengshuonan
	 * @return String 交易内容
	 */
	private String getTradContent(int type) {
		String tradContent = "";

		switch (type) {
		case 1:
			tradContent = "洗车券";
			break;
		case 2:
			tradContent = "现金券";
			break;
		case 3:
			tradContent = "折扣券";
			break;
		case 4:
			tradContent = "实物商品";
		}

		return tradContent;
	}

	/**
	 * @Title: getUserIntegraDetailRecordList
	 * @Description:根据用户id获取用户积分记录
	 * @param @param
	 *            userId
	 * @author zhouxuan
	 * @return List<UserIntegraDetailRecordRes>
	 */
	public List<UserIntegraDetailRecordRes> getUserIntegraDetailRecordList(String userId, int row, int pageSize) {
		// 构造分页参数
		GetUserIntegralDetailDTO getUserIntegralDetailDTO = new GetUserIntegralDetailDTO();
		getUserIntegralDetailDTO.setUserId(userId);
		getUserIntegralDetailDTO.setRow(row);
		getUserIntegralDetailDTO.setPageSize(pageSize);

		// 获取用户积分记录列表
		List<Userintegraldetail> userintegraldetails = this.userIntegralService
				.getUserIntegralDetail(getUserIntegralDetailDTO);

		if (userintegraldetails == null) {
			return null;
		}

		// 构造响应列表
		List<UserIntegraDetailRecordRes> lists = new ArrayList<UserIntegraDetailRecordRes>();

		for (Userintegraldetail userintegraldetail : userintegraldetails) {
			UserIntegraDetailRecordRes temp = new UserIntegraDetailRecordRes();
			if (userintegraldetail.getTradeMoney() == null) {
				userintegraldetail.setTradeMoney(new BigDecimal(0));
			}
			if (userintegraldetail.getTradeContent() == null) {
				userintegraldetail.setTradeContent("");
			}
			temp.setTradeType(userintegraldetail.getTradeType());
			temp.setTradeMoney(userintegraldetail.getTradeMoney());
			temp.setTradeContent(userintegraldetail.getTradeContent());
			temp.setTradaTime(userintegraldetail.getTradeTime());
			lists.add(temp);
		}
		return lists;
	}

}
